package smedi.ismedi.web.bff.controller.authortiy;

import com.smedi.ismedi.authoritymanagement.api.dto.response.PersonRoleRelationshipResponse;
import com.smedi.ismedi.authoritymanagement.api.feign.RemoteAuthorityRoleManagementFeignApi;
import com.smedi.ismedi.constructionproject.api.feign.RemoteProjectAssignmentFeignApi;
import com.smedi.ismedi.personnel.api.dto.response.PersonSimpleResponse;
import com.smedi.ismedi.personnel.api.feign.RemotePersonCoreFeignApi;
import com.smedi.ismedi.web.starter.common.ResponseData;
import com.smedi.ismedi.web.starter.exception.LogicException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import smedi.ismedi.web.bff.dto.RoleRelationshipResponse;
import smedi.ismedi.web.bff.infrastructure.constant.CustomError;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author: xulinjun
 * @Date: 2021-7-4 15:45
 */
@Slf4j
@RestController
@Api(tags = {"角色人员选择接口"})
@RequestMapping("/webbff/v1/authorityRolePickerPerson")
@AllArgsConstructor
public class AuthorityRolePickerPersonController {
    private final RemotePersonCoreFeignApi remotePersonCoreFeignApi;

    private final RemoteAuthorityRoleManagementFeignApi remoteAuthorityRoleManagementFeignApi;

    private final RemoteProjectAssignmentFeignApi remoteProjectAssignmentFeignApi;

    /**
     * 设置角色页面点击企业组织显示企业组织下人员及角色分配情况
     *
     * @param hrOrganizationId
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "设置角色页面点击企业组织显示企业组织下人员及角色分配情况")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "hrOrganizationId", value = "企业组织id", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(paramType = "query", name = "roleId", value = "角色id", dataType = "Long", dataTypeClass = Long.class),
    })
    @GetMapping(value = "/getPersonRoleRelationshipByCurrentHrOrganizationId")
    public ResponseData<List<RoleRelationshipResponse>> getPersonRoleRelationshipByCurrentHrOrganizationId(@RequestParam("hrOrganizationId") Long hrOrganizationId, @RequestParam("roleId") Long roleId) {
        ResponseData<List<PersonSimpleResponse>> personResponse = remotePersonCoreFeignApi.getQueryPersonSimpleByCurrentHrOrganizationId(hrOrganizationId);
        if (!personResponse.isSuccess()) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, personResponse.getApplication(), String.valueOf(personResponse.getErrorMsg()));
        }
        List<Long> personIds = personResponse.getData().stream().map(PersonSimpleResponse::getPersonId).collect(Collectors.toList());

        // 获取这些人员id是否有权限分配
        ResponseData<List<PersonRoleRelationshipResponse>> roleResponse = remoteAuthorityRoleManagementFeignApi.getQueryPersonRoleRelationshipByPersonIds(personIds, roleId);
        if (!roleResponse.isSuccess()) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, roleResponse.getApplication(), String.valueOf(roleResponse.getErrorMsg()));
        }

        List<RoleRelationshipResponse> list = new ArrayList<>();
        personResponse.getData().forEach(person -> {
            Optional<PersonRoleRelationshipResponse> optional = roleResponse.getData().stream().filter(role -> role.getPersonId().equals(person.getPersonId())).findFirst();
            if (optional.isPresent()) {
                list.add(new RoleRelationshipResponse()
                        .setPersonId(person.getPersonId())
                        .setLastName(person.getLastName())
                        .setHasRole(optional.get().isHasRole()));
            }
        });
        return new ResponseData<List<RoleRelationshipResponse>>().success(list);
    }

    @ApiOperation(httpMethod = "GET", value = "设置角色页面点击项目组织显示项目组织下人员及角色分配情况")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "projectOrganizationId", value = "项目组织id", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(paramType = "query", name = "roleId", value = "角色id", dataType = "Long", dataTypeClass = Long.class),
    })
    @GetMapping(value = "/getPersonRoleRelationshipByCurrentProjectOrganizationId")
    public ResponseData<List<RoleRelationshipResponse>> getPersonRoleRelationshipByCurrentProjectOrganizationId(@RequestParam("projectOrganizationId") Long projectOrganizationId, @RequestParam("roleId") Long roleId) {
        ResponseData<List<Long>> personIdsResponse = remoteProjectAssignmentFeignApi.getQueryPersonSimpleByCurrentProjectOrganizationId(projectOrganizationId);
        if (!personIdsResponse.isSuccess()) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, personIdsResponse.getApplication(), String.valueOf(personIdsResponse.getErrorMsg()));
        }
        List<Long> personIds = personIdsResponse.getData();

        // 根据人员id获取基本信息
        ResponseData<List<PersonSimpleResponse>> personSimpleResponse = remotePersonCoreFeignApi.getQueryPersonSimpleList(personIds);
        if (!personSimpleResponse.isSuccess()) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, personSimpleResponse.getApplication(), String.valueOf(personSimpleResponse.getErrorMsg()));
        }

        // 获取这些人员id是否有权限分配
        ResponseData<List<PersonRoleRelationshipResponse>> roleResponse = remoteAuthorityRoleManagementFeignApi.getQueryPersonRoleRelationshipByPersonIds(personIds, roleId);
        if (!roleResponse.isSuccess()) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, roleResponse.getApplication(), String.valueOf(roleResponse.getErrorMsg()));
        }

        List<RoleRelationshipResponse> list = new ArrayList<>();
        personSimpleResponse.getData().forEach(person -> {
            Optional<PersonRoleRelationshipResponse> optional = roleResponse.getData().stream().filter(role -> role.getPersonId().equals(person.getPersonId())).findFirst();
            if (optional.isPresent()) {
                list.add(new RoleRelationshipResponse()
                        .setPersonId(person.getPersonId())
                        .setLastName(person.getLastName())
                        .setHasRole(optional.get().isHasRole()));
            }
        });

        return new ResponseData<List<RoleRelationshipResponse>>().success(list);
    }
}
